package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/*
服务端的练习和完善，
 */
public class ServerPlus3 {
    private ServerSocket serverSocket;

    public ServerPlus3(){
        try {
            serverSocket = new ServerSocket(9090);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            while (true) {
                System.out.println("等待连接");
                Socket socket = serverSocket.accept();
                System.out.println("连接成功");
                Runnable r = new ClientHandler(socket);
                Thread t = new Thread(r);
                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        ServerPlus3 sp = new ServerPlus3();
        sp.start();
    }

    private  class ClientHandler implements Runnable{
        private Socket socket;
        private String name;
        public ClientHandler(Socket socket){
            this.socket=socket;
            this.name=socket.getInetAddress().getHostName();
        }
        @Override
        public void run() {

            try {
                //读
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                //原数据返回
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os,StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                PrintWriter pw = new PrintWriter(bw,true);

                String temp;
                while ((temp = br.readLine())!=null){
                    System.out.println(name +":" +temp);
                    //将读取到的消息回复给客户端
                    pw.println(temp);
                }
                br.close();
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
